< previous page page_334 next page >

Page 334
e10a6a0a59f035e870d90cca05b85fce.gif
        (B * B - A * num_points)
    b_value = (B * C - A * D) / _
        (B * B - A * num_points)
End Sub

' Draw the least squares line.
Private Sub DrawCurve()
Dim m_value As Single
Dim b_value As Single
Dim x1 As Single
Dim x2 As Single
Dim y1 As Single
Dim y2 As Single
Dim i As Integer

    ' Get the m and b values for the line.
    GetLeastSquaresValues PtX, PtY, m_value, b_value

    ' Find the minimum and maximum X values.
    x1 = PtX(1)     ' This will be the minimum X value.
    x2 = x1         ' This will be the maximum X value.
    For i = 2 To numpts
        If x1 > PtX(i) Then x1 = PtX(i)
        If x2 < PtX(i) Then x2 = PtX(i)
    Next i

    ' Draw the line.
    y1 = m_value * x1 + b_value
    y2 = m_value * x2 + b_value
    picCanvas.Line (x1, y1)-(x2, y2)
End Sub
Example program LeastSq uses this code to display a linear least squares fit to a set of points. Click several times in the drawing area to select some points. When you click the Go button, the program displays the least squares line. It then resets itself so that you can start clicking to create a new set of points. Figure 11.9 shows program LeastSq fitting a least squares line to a set of data points.
Quadratic Least Squares
You can use techniques similar to those described in the previous section to fit a higherorder polynomial to fit a set of data points. For instance, you might believe your data has a shape that fits an equation like a * x2 + b * x + c rather than a line. In that case, you can write the sum of the squares of the differences between the curve and the data points as:
e10a6a0a59f035e870d90cca05b85fce.gif
E(a, b, c) = S (a * xi2 + b * xi + c - yi)2

 
< previous page page_334 next page >